package com.epoint.webapp.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.epoint.webapp.dao.MemberDAO;
import com.epoint.webapp.dao.UploadImageDAO;
import com.epoint.webapp.entity.UploadImage;
import com.epoint.webapp.util.DateConversion;
import com.epoint.webapp.util.FileUtil;

@Controller
public class ManageImageController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	
	@RequestMapping(value = "management/uploadManageImage", method = RequestMethod.POST)
	public @ResponseBody String uploadImage(HttpSession session, MultipartFile upload, HttpServletRequest request) throws Exception {
		
		
		
		String printString = "";
		if(upload.getSize() > 0){
			String path = session.getServletContext().getRealPath("resources/manageImage/");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			FileUtil fileUtil = new FileUtil(upload.getOriginalFilename());
			String newFileName = dateConversion.ConversionYMDHMS2(now) + "." + fileUtil.getFileType();
			File targetFile = new File(path, newFileName);
	        if(!targetFile.exists()){
	            targetFile.mkdirs();
	        }
	        try {
	        	upload.transferTo(targetFile);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        
	        String url = "http://localhost:8080/Epoint/resources/manageImage/" + newFileName;
	        
			printString += "<script type=\'text/javascript\'>";
			printString += "window.parent.CKEDITOR.tools.callFunction(1,'"+url+"','')";
			printString += "</script>";
		}
		return printString;		
		
	}
}
